<template>
    <div class="synchronize-saving">
        <cite>
            <button @click="doCancel()" v-text="backButton"></button>
            <button @click="doCotinue()" :class="{ disabled: disabled }" type="primary" v-text="nextButton"></button>
            <p>
                <!-- 再次编辑时不可以保存为草稿 -->
                <a @click="doDraft()" v-show="!/detail|price/.test(status.action) ">Save as draft</a>
                <!-- <span>This product will not be posted to the store</span> -->
            </p>
        </cite>
    </div>
</template>

<script>
import { mapGetters, mapState } from "vuex";
export default {
    name: "StoreSave",
    props: {
        disabled: { type: Boolean, default: false },
    },
    data () {
        return {
        };
    },
    computed: {
        ...mapState("synchronize", {
            status: "status",
        }),

        // 返回按钮
        backButton () {
            if (this.status.action == "resave") {
                // 草稿二次编辑
                return this.status.step > 2 ? 'Back' : 'Cancel';
            } else if (this.status.action == 'create') {
                // 创建
                return this.status.step > 1 ? 'Back' : 'Cancel';
            } else {
                // 其他情况下的二次编辑
                return "Cancel";
            }
        },

        // 继续按钮
        nextButton () {
            if (/detail|price/.test(this.status.action)) {
                // 二次编辑
                return "Continue to publish";
            } else {
                return {
                    "1": "Proceed to details",
                    "2": "Proceed to set prices",
                    "3": "Continue to publish",
                }[this.status.step]
            }
        },
    },
    methods: {

        // 跳转到下个流程
        doCancel () {
            if (this.status.action == "resave") {
                // 草稿二次编辑
                if (this.status.step == 2) {
                    this.$router.go(-1);
                } else {
                    this.status.step -= 1;
                }
            } else if (this.status.action == 'create') {
                // 创建
                if (this.status.step == 1) {
                    this.$router.go(-1);
                } else {
                    this.status.step -= 1;
                }
            } else {
                // 其他情况下的二次编辑
                // return "Cancel";
                this.$router.go(-1);
            }
        },

        //next
        doCotinue () {
            this.$emit('global:SYNCHRONIZE_CHECK').then(e => {
                if (/detail|price/.test(this.status.action)) {
                    // 重新保存
                    this.$emit('save', 'update')
                } else if (this.status.step >= 3) {
                    // 创建
                    this.$emit('save', this.status.action == 'create' ? 'create' : 'update')
                } else {
                    this.status.step += 1;
                    document.body.scrollTop = document.documentElement.scrollTop = 0;
                }
            }).catch(error => {
                console.log(error)
            })
        },

        // 保存草稿
        doDraft () {
            this.$emit('global:SYNCHRONIZE_CHECK').then(e => this.$emit('save', 'draft'))
        },

        /*
        // 初始化价格展示
        setVariants () {
            this.$store.dispatch("synchronize/setVariants");
        },

        // 四舍五入取整
        mathRound (value, n) {
            let bei = Math.pow(10, n);
            let res = Math.round(value * bei) / bei;
            return +parseFloat(res.toPrecision(12));
        },

        // 取价格表
        getVariants () {
            let result = this.variants.map((item) => {
                return {
                    color: item.color,
                    size: item.size,
                    cost: this.mathRound(item.cost, 0), // 原价
                    retail_price: this.mathRound(item.retail, 0), // 零售价
                    sku: item.sku,
                    disabled: !!item.disabled,
                };
            });
            return result;
        },

        getDescription () {

            let html = this.info.description;

            // etsy的富文本不能有标签
            if (this.info.shop_type == 2) {
                // 块元素变换行
                html = html.replace(/<(li|div|p)[^\>]*?>/g, "<br>");
                // 换行元素转\n
                html = html.replace(/(<br\/?>)+/g, "\n");
                // 其他元素去掉
                html = html.replace(/<\/?.+?>/g, "");
                // 去重复换行
                html = html.replace(/(\r?\n)+/g, "\n");
                // 去头尾换行
                html = html.replace(/(^\n|\n$)/g, "");

                return html;
            } else {
                return html;
            }

        },

        // 获取参数
        getRequest () {
            // color 要排序，选中的basecolor要放在最前面
            // let color = this.selectColor.filter((i) => i != this.baseColor);

            const tag = this.info.tag_design_info;
            const pack = this.info.pack_design_info;

            const request = {
                title: this.info.title,
                body_html: this.getDescription(),
                vendor: "podpartner",
                product_collection_id: this.info.product_collection_id, // shopify 分类id ，number类型
                product_collection: this.info.product_collection, // wix 分类id string类型
                size: this.selectSizes, // 选中的尺码
                // color: [this.baseColor].concat(color), // 选中的颜色
                color: [], // 选中的颜色
                model: this.baseModel, // 选中的主要模特图片
                base_color: this.baseColor, // 选中的主要基础色
                image_urls: "", // 颜色与模特合并图片
                variants: this.getVariants(),
                size_guide: this.info.size_guide, // 尺码位置
                display: this.info.display, // 是否在商店中显示
                taxonomy_id: this.info.taxonomy_id,
                is_new_shipping: this.info.is_new_shipping,
                shipping_profile_id: this.info.shipping_profile_id,
                img_size_url: this.info.size_url,
                tag_design_id: tag ? tag.id : 0,
                pack_design_id: pack ? pack.id : 0,
            }

            if (this.info.shop_type != 3) {
                // wix 不需要传tags
                request.tags = this.info.tags
            }

            return request
        },

        // 合成图片
        async getImageUrls () {
            const cache = this.cache || {};
            const result = {
                colors: [],
                format: [],// 格式化输出，二维数据, 主颜色放第一个,其他颜色按顺序向后面排
            }

            const baseColorObject = this.baseColorObject || {};
            const baseModelObject = this.baseModelObject || {};
            const selectColorObject = this.selectColorObject || [];
            const selectModelObject = this.selectModelObject || [];

            // 要生成的数据
            const drawerObject = {};

            // 要生成的图片列表
            const drawerList = [];

            // 基础颜色加所有的模特
            // 基础模特加所有颜色
            selectColorObject.map((color) => {
                const id = color.color_id + "-" + baseModelObject.model_url;
                drawerObject[id] = {
                    color: color,
                    model: baseModelObject,
                    result: "",
                };
            });

            selectModelObject.map((model) => {
                const id = baseColorObject.color_id + "-" + model.model_url;
                drawerObject[id] = {
                    color: baseColorObject,
                    model: model,
                    result: "",
                };
            });

            Object.keys(drawerObject).map((key) => {
                if (cache[key]) {
                    // 缓存中已经有了
                    drawerObject[key].result = cache[key];
                } else {
                    const drawer = drawerObject[key] || {};
                    const model = drawer.model || {};
                    const color = drawer.color || {};
                    const surface = (model.surface_name || '').toLowerCase();
                    const name = (surface.match(/^\S+/g) || [])[0] || '';

                    drawerList.push({
                        id: key,
                        color: this.$modelBackgroundColor(color.color_num, model),
                        taxture: color['bg_' + name] || '',
                        model: drawer.model.model_url,
                    });
                }
            });


            if (drawerList.length > 0) {
                let request = {
                    shop_id: this.ids.shop_id,
                    drawer_list: drawerList,
                };
                let response = await this.$http("Drawer.batchDrawModelBackground", request);

                if (response.code === 0) {
                    const result = response.data || [];
                    drawerList.map((item, index) => {
                        const drawer = drawerObject[item.id] || {};
                        const output = (result[index] || {}).result
                        drawer.result = output;
                    });
                }
            }


            // 按颜色顺序
            this.colorList.map((color) => {
                if (this.selectColor.indexOf(color.color_id) < 0) {
                    // 如果没有在内部
                } else if (color.color_num == baseColorObject.color_num) {
                    const baseList = [];
                    // 主颜色加所有的模特
                    selectModelObject.map((model) => {
                        const id = color.color_id + "-" + model.model_url;
                        const drawer = drawerObject[id];
                        // 如果是主模特，则放在第一个
                        if (model.model_url == baseModelObject.model_url) {
                            baseList.unshift(drawer.result);
                        } else {
                            baseList.push(drawer.result);
                        }
                    });
                    result.format.unshift(baseList);
                    result.colors.unshift(color.color_id);
                } else {
                    const id = color.color_id + "-" + baseModelObject.model_url;
                    const drawer = drawerObject[id];
                    result.format.push([drawer.result]);
                    result.colors.push(color.color_id);
                }
            });

            return result;
        },

        // 更新草稿信息
        async updateProduct (update) {
            this.loading = this.$loading({ lock: true, text: "Loading..." });
            const request = this.getRequest();
            const drawer = await this.getImageUrls();

            request.shop_id = parseInt(this.ids.shop_id) || 0;
            request.design_id = parseInt(this.ids.design_id) || 0;
            request.product_id = parseInt(this.ids.product_id) || 0;
            request.id = parseInt(this.ids.goods_id) || 0;
            request.image_urls = drawer.format || [];
            request.color = drawer.colors || [];

            if (request.image_urls.length <= 0) {
                // 图片生成失败
                this.loading.close();
                this.loading = null;
                this.$uxMessage.error(
                    "Failed to generate image, please try again later"
                );
            } else {
                request.id = this.ids.goods_id;

                let response = await this.$http(
                    "UserStore.putGoodPublish",
                    request
                );
                if (response.code === 0) {
                    if (update) {
                        // 同步到商店
                        await this.asyncPublish(this.ids.goods_id);
                    } else {
                        this.$uxMessage.success("Draft saved successfully");
                    }
                    // 跳转
                    this.$emit("setCache");
                    this.$router.go(-1);
                    this.loading.close();
                    this.loading = null;
                } else {
                    this.$uxMessage.error(response.msg || "Failed to save draft");
                    // 提示
                    this.loading.close();
                    this.loading = null;
                }
            }
        },

        // 添加
        async insertPublish (update) {
            this.loading = this.$loading({ lock: true, text: "Loading..." });
            const request = this.getRequest();
            const drawer = await this.getImageUrls();
            request.shop_id = parseInt(this.ids.shop_id) || 0;
            request.design_id = parseInt(this.ids.temp_id) || 0;
            request.product_id = parseInt(this.ids.product_id) || 0;
            request.image_urls = drawer.format || [];
            request.color = drawer.colors || [];

            if (request.image_urls.length <= 0) {
                // 图片生成失败
                this.loading.close();
                this.loading = null;
                this.$uxMessage.error(
                    "Failed to generate image, please try again later"
                );
            } else {
                let response = await this.$http(
                    "UserStore.setGoodPublish",
                    request
                );
                if (response.code === 0) {
                    if (update && response.data && response.data.id) {
                        await this.asyncPublish(response.data.id, true);
                    } else {
                        this.$uxMessage.success("Draft saved successfully");
                    }

                    // 跳转
                    this.$emit("setCache");
                    this.$router.push("/user/store?shop_id=" + request.shop_id);
                    this.loading.close();
                    this.loading = null;
                } else {
                    this.$uxMessage.error(response.msg || "Failed to save draft");
                    // 提示
                    this.loading.close();
                    this.loading = null;
                }
            }
        },

        // 更新到店铺
        async asyncPublish (id, insert) {
            const shopname = {
                '1': 'shopify',
                '2': 'etsy',
                '3': 'wix'
            };
            const name = shopname[this.info.shop_type] || 'store online';
            const result = await this.$http("UserStore.syncProduct", id);
            if (result.code === 0) {
                // this.$uxMessage.success("Your product is being synced to " + name);
            } else {
                this.$uxMessage.error("Failed to sync product");
            }
        },

        */



    },
    mounted () {
        // this.setCache()
        // this.cache = JSON.stringify(this.request);
    },
};
</script>

<style lang="scss" scoped>
.synchronize-saving {
    max-width: 1140px;
    padding: 0 20px;
    box-sizing: border-box;
    margin: 0 auto;
    width: 100%;
    cite {
        position: relative;
        z-index: 2;
        width: 100%;
        padding: 24px 0;
        border-top: 1px solid #dcdcdc;
        box-sizing: border-box;
        background: #fff;
        display: flex;
        justify-content: flex-end;
        flex-wrap: wrap;

        button {
            position: relative;
            text-align: center;
            padding: 0;
            height: 40px;
            border-radius: 6px;
            margin: 0 0 0 16px;
            &.disabled {
                pointer-events: none;
            }
        }

        button:nth-child(1) {
            width: 140px;
        }

        button:nth-child(2) {
            width: 220px;
        }

        p {
            width: 100%;
            height: 16px;
            font-size: 14px;
            color: #000000;
            line-height: 16px;
            text-align: right;
            margin-top: 16px;
            a {
                text-decoration: underline;
                cursor: pointer;
                margin: 0 12px 0 0;
                font-size: 14px;
                font-family: Roboto-Regular, Roboto;
                font-weight: 400;
                color: #555555;
                line-height: 16px;

                color: #555555;
                &:hover {
                    color: #ea4c89;
                }
            }
        }
    }
}
</style>

<style>
.saving-svg {
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 999;
    background: #fff;
}
.saving-svg table {
    width: 1200px;
    line-height: 40px;
    border-collapse: collapse;
    table-layout: fixed;
}
.saving-svg table th {
    text-align: center;
    background: rgba(0, 0, 0, 0.05);
    border: 1px solid #ddd;
    font-weight: normal;
}
.saving-svg table th::first-child {
    width: 160px;
}
.saving-svg table td {
    text-align: center;
    border: 1px solid #ddd;
}
.saving-svg table + table {
    margin-top: 40px;
}
.saving-svg p {
    padding: 16px 0;
    line-height: 32px;
    text-align: center;
    font-size: 18px;
}
</style>
